<script lang="jsx" setup>
import { computed, watch, inject, ref } from 'vue';
import { Button } from 'ant-design-vue';
import { SearchOutlined } from '@ant-design/icons-vue';
import { REQU, useResp, SignInInfoInvalidCondPair } from '@/net/requ.js';
import { strToArr, isNewPatternClasses, xsToOpts } from '@/util/index.js';
import * as storage from '@/util/storage.js';
import router from '@/router/index.js';
import { onBeforeRouteLeave } from 'vue-router';

const taskInfo = inject('taskInfo');
watch(
  taskInfo,
  () => {
    params.value.taskIds = taskInfo.value.id;
    getQuesList();
  },
  { deep: true }
);

onBeforeRouteLeave((to, from, next) => {
  const labelPathList = ['/obj-detn', '/seq-label', '/text-classification'];
  const isNotToLabel = () => R.compose( R.not, R.includes(to.path) )(labelPathList);
  isNotToLabel() && localStorage.removeItem('pkgInfo');
  next();
});

const loading = ref(false);

const params = ref(
  storage.readAsObj('ques-search')
  || {
    taskIds: taskInfo.value?.id,
    labelName: '',
    cateName: '',
    orderField: 'file_name',
    orderType: 'ASC',
    queryString: '',
    start: 1,
    limit: 10,
  }
);

watch(
  () => params.value.queryString,
  () => (params.value.start = 1)
);

watch(params, storage.writeAsStr('ques-search'), { deep: true });

const pagination = ref({
  total: 0,
  position: ['bottomCenter'],
  get current() {
    return params.value.start;
  },
  get pageSize() {
    return params.value.limit;
  },
  onChange: page => {
    params.value.start = page;
  },
});
watch(() => pagination.value.current, getQuesList);

const filterOption = (input, opt) => opt.value.includes(input);

const classes = computed(() => (
  R.ifElse(
    isNewPatternClasses,
    R.compose( R.pluck('label'), R.curryN(1, JSON.parse) ),
    strToArr(R.split(','))
  )(R.propOr('', 'labels', taskInfo.value))
));

// table

const RoutePath = R.prop(R.__, {
  '1': '/obj-detn',
  '11': '/obj-detn',
  '12': '/video-action',
  '21': '/seq-label',
  '23': '/text-classification',
});

const OpBtn = record => operate => (
  <Button
    v-exist:task={operate}
    type="primary"
    ghost
    shape="round"
    size="small"
    onClick={() => {
      storage.write('operate', operate);
      storage.writeAsStr('pkgInfo', { ques: record.id });
      router.push({ path: RoutePath(taskInfo.value.type), query: { mode: 'search' } });
    }}>
    {{ default: () => operate }}
  </Button>
);

const OpBtnCol = ({ record }) => (
  <div class="op-btns">
    {R.map(OpBtn(record), ['标注', '查看', '审核'])}
  </div>
);

const columns = ref([
  {
    ellipsis: true,
    title: '文件名称',
    dataIndex: 'fileName',
  },
  {
    title: '提交时间',
    width: 170,
    dataIndex: 'submitTime',
    customRender: ({ text }) => text || '--'
  },
  {
    width: 90,
    ellipsis: true,
    title: '验收员',
    dataIndex: 'auditUserId',
    customRender: ({ record }) => record.auditUserName,
  },
  {
    title: '验收时间',
    width: 170,
    dataIndex: 'auditTime',
  },
  {
    ellipsis: true,
    width: 386,
    title: '驳回理由',
    dataIndex: 'remark',
    customRender: ({ text }) => text || '--',
  },
  {
    title: '题状态',
    dataIndex: 'auditStatus',
    width: 90,
    customRender: ({ text }) => {
      const Color = R.prop(R.__, { 1: 'green', 2: 'rgb(200,0,0)' });
      const Txt = R.propOr('待验收', R.__, { 1: '验收通过', 2: '验收驳回' });
      return (<span style={{ color: Color(text) }}>{Txt(text)}</span>);
    },
  },
  {
    title: '操作',
    width: 200,
    customRender: OpBtnCol,
  },
]);

const dataSource = ref([]);

function getQuesList() {
  if (!taskInfo.value?.id) { return; }
  
  loading.value = true;
  // a-select allow-clear 会使字段值为 undefined，导致值会转 'undefined'
  REQU(`/api/taskAssignmentPackageFile/list?${ new URLSearchParams(
    R.filter(R.isNotNil, params.value)
  ) }`)
  .then(useResp({
    succ: result => {
      dataSource.value = result.data.list;
      pagination.value.total = result.data.total;
      storage.write('quesTotal', result.data.total);
    },
    fail: R.cond([
      SignInInfoInvalidCondPair(),
      [
        R.T,
        () => {
          dataSource.value = [];
          pagination.value.total = 0;
          storage.write('quesTotal', 0);
        }
      ],
    ]),
  }))
  .finally(() => loading.value = false);
}

function main() {
  getQuesList();
}

main();
</script>

<template>
  <a-form
    layout="inline"
    :colon="false"
    style="display: flex; margin-bottom: 1em;">
    <a-form-item label="文件名">
      <a-input
        v-model:value="params.queryString"
        placeholder="请输入文件名"
        allow-clear>
      </a-input>
    </a-form-item>
    <a-form-item label="标签">
      <a-select
        v-model:value="params.labelName"
        placeholder="请选择标签"
        allow-clear
        :options="xsToOpts(classes)"
        show-search
        :dropdown-match-select-width="false"
        :filter-option="filterOption"
        style="width: 112px;"
      >
      </a-select>
    </a-form-item>

    <a-form-item>
      <a-button
        shape="circle"
        html-type="submit"
        @click="() => getQuesList()"
        :disabled="loading">
        <template #icon><search-outlined /></template>
      </a-button>
    </a-form-item>

    <a-button
      :disabled="loading"
      @click="() => {
        params.queryString = '';
        params.labelName = '';
        getQuesList();
      }">
      重置
    </a-button>
  </a-form>

  <a-config-provider :auto-insert-space-in-button="false">
    <a-table
      :loading="loading"
      :columns="columns"
      :data-source="dataSource"
      :pagination="pagination"
      :scroll="{ x: 1360 }"
    >
    </a-table>
  </a-config-provider>
</template>
